/**
 * 页面跳转工具类
 * 用于统一管理页面跳转，避免WebView数量超限问题
 */

// 页面跳转状态管理
let isNavigating = false
let navigationQueue = []
let maxRetryCount = 3

// 页面栈深度检查
const checkPageStackDepth = () => {
  try {
    const pages = getCurrentPages()
    return pages.length
  } catch (error) {
    console.warn('无法获取页面栈信息:', error)
    return 0
  }
}

// 智能选择跳转方式
const selectNavigationMethod = (url, options = {}) => {
  const currentDepth = checkPageStackDepth()
  const maxDepth = 8 // 设置最大页面栈深度
  
  // 如果页面栈过深，使用 redirectTo 或 reLaunch
  if (currentDepth >= maxDepth) {
    if (options.forceNavigate) {
      // 强制使用 navigateTo，但会先清理一些页面
      return 'navigateToWithCleanup'
    } else {
      return 'redirectTo'
    }
  }
  
  // 根据跳转目标选择合适的方式
  if (options.replaceCurrent) {
    return 'redirectTo'
  }
  
  if (options.restart) {
    return 'reLaunch'
  }
  
  return 'navigateTo'
}

// 清理页面栈（保留当前页面和首页）
const cleanupPageStack = () => {
  try {
    const pages = getCurrentPages()
    if (pages.length > 2) {
      // 保留当前页面和首页，清理中间的页面
      const currentPage = pages[pages.length - 1]
      const homePage = pages[0]
      
      // 这里可以通过设置页面栈来清理，但需要谨慎操作
      console.log('页面栈深度过高，建议使用 redirectTo 或 reLaunch')
    }
  } catch (error) {
    console.warn('清理页面栈失败:', error)
  }
}

// 执行页面跳转
const executeNavigation = (method, url, options = {}) => {
  return new Promise((resolve, reject) => {
    const navigationConfig = {
      url,
      success: (res) => {
        isNavigating = false
        console.log(`页面跳转成功: ${method} -> ${url}`)
        resolve(res)
        // 处理队列中的下一个跳转
        processNavigationQueue()
      },
      fail: (err) => {
        isNavigating = false
        console.error(`页面跳转失败: ${method} -> ${url}`, err)
        
        // 如果是 WebView 数量超限，尝试其他跳转方式
        if (err.errMsg && err.errMsg.includes('webview count limit exceed')) {
          console.warn('WebView数量超限，尝试使用 redirectTo')
          executeNavigation('redirectTo', url, options)
            .then(resolve)
            .catch(reject)
        } else {
          reject(err)
        }
      }
    }

    switch (method) {
      case 'navigateTo':
        uni.navigateTo(navigationConfig)
        break
      case 'redirectTo':
        uni.redirectTo(navigationConfig)
        break
      case 'reLaunch':
        uni.reLaunch(navigationConfig)
        break
      case 'navigateToWithCleanup':
        cleanupPageStack()
        uni.navigateTo(navigationConfig)
        break
      default:
        uni.navigateTo(navigationConfig)
    }
  })
}

// 处理导航队列
const processNavigationQueue = () => {
  if (navigationQueue.length > 0 && !isNavigating) {
    const nextNavigation = navigationQueue.shift()
    executeNavigation(
      nextNavigation.method,
      nextNavigation.url,
      nextNavigation.options
    )
  }
}

// 添加防抖的页面跳转
const debouncedNavigate = (() => {
  let timer = null
  return (method, url, options = {}) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      navigateTo(method, url, options)
    }, 100) // 100ms 防抖
  }
})()

// 主要跳转方法
export const navigateTo = (method, url, options = {}) => {
  // 如果正在跳转中，加入队列
  if (isNavigating) {
    navigationQueue.push({ method, url, options })
    return Promise.resolve()
  }

  isNavigating = true
  
  // 智能选择跳转方式
  const selectedMethod = selectNavigationMethod(url, options)
  
  return executeNavigation(selectedMethod, url, options)
}

// 便捷方法
export const goTo = (url, options = {}) => {
  return navigateTo('navigateTo', url, options)
}

export const goToReplace = (url, options = {}) => {
  return navigateTo('redirectTo', url, options)
}

export const goToRestart = (url, options = {}) => {
  return navigateTo('reLaunch', url, options)
}

// 带防抖的跳转
export const goToDebounced = (url, options = {}) => {
  return debouncedNavigate('navigateTo', url, options)
}

// 返回上一页
export const goBack = (delta = 1) => {
  return new Promise((resolve, reject) => {
    uni.navigateBack({
      delta,
      success: resolve,
      fail: reject
    })
  })
}

// 返回首页
export const goHome = () => {
  return new Promise((resolve, reject) => {
    uni.switchTab({
      url: '/pages/studentsPage/student-index',
      success: resolve,
      fail: reject
    })
  })
}

// 获取当前页面信息
export const getCurrentPageInfo = () => {
  try {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    return {
      route: currentPage?.route,
      depth: pages.length,
      canGoBack: pages.length > 1
    }
  } catch (error) {
    console.warn('获取当前页面信息失败:', error)
    return {}
  }
}

// 检查是否可以跳转
export const canNavigate = () => {
  return !isNavigating && checkPageStackDepth() < 8
}

// 重置导航状态
export const resetNavigation = () => {
  isNavigating = false
  navigationQueue = []
}

export default {
  navigateTo,
  goTo,
  goToReplace,
  goToRestart,
  goToDebounced,
  goBack,
  goHome,
  getCurrentPageInfo,
  canNavigate,
  resetNavigation
}
